package edu.byu.intex2.javamail;

/**
 * Send Mail through SMTP Server
 * @author Brady White
 */
import java.util.Properties;

import javax.mail.*;
import javax.mail.Message.RecipientType;
import javax.mail.internet.*;

public class SendMail {

    private String from;
    private String[] recipients;
    private String subject;
    private String text;

    /** Constructor */
    public SendMail(String from, String[] to, String subject, String text) {
        this.from = from;
        this.recipients = to;
        this.subject = subject;
        this.text = text;
    }

    /**
     * Send our email
     */
    public void send() {
        // Properties to define the mail session
        Properties props = new Properties();
        props.put("mail.smtp.host", "gateway.byu.edu");
//        props.put("mail.smtp.host", "smtp.gmail.com");
//        props.put("mail.smtp.starttls.enable", "true"); // Gmail requires TTLS during the session

        // Authenticate with SMTP
        String protocol = "smtp";
//        props.put("mail." + protocol + ".auth", "true");

        // Authenticator for Gmail's SMTP Server
        Authenticator auth = new SMTPAuthenticator();

        // Mail Session
        Session mailSession = Session.getDefaultInstance(props, auth);
        Message simpleMessage = new MimeMessage(mailSession);

        // Internet Addresses
        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        InternetAddress fromAddress = null;

        try {
            fromAddress = new InternetAddress(from);
            for (int i = 0; i < recipients.length; i++) {
                addressTo[i] = new InternetAddress(recipients[i]);
            }
        } catch (AddressException e) {
            e.printStackTrace();
        }


        try {
            // Define Email Message
            simpleMessage.setFrom(fromAddress);
            simpleMessage.setRecipients(RecipientType.TO, addressTo);
            simpleMessage.setSubject(subject);
            simpleMessage.setText(text);

            // Send Email
            Transport.send(simpleMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }
}
